package common.com.androidbase.datarequest;

import com.common.sdk.net.connect.http.center.tools.HttpLog;
import com.common.sdk.net.connect.http.interceptor.ExceptionCatchedInterceptor;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by chengjiangsang116630 on 2018/1/30.
 */

public class LoggingInterceptor extends ExceptionCatchedInterceptor {

    private static final String TAG = "LoggingInterceptor";

    @Override
    protected Response realIntercept(Chain chain) throws IOException {
        //这个chain里面包含了request和response，所以你要什么都可以从这里拿
        Request request = chain.request();

        long t1 = System.nanoTime();//请求发起的时间
        StringBuilder sb = new StringBuilder();
        RequestBody requestBody = request.body();
        if (requestBody instanceof FormBody) {
            FormBody formBody = (FormBody) requestBody;
            for(int i=0; i<formBody.size(); i++) {
                sb.append(formBody.encodedName(i));
                sb.append(":");
                sb.append(formBody.encodedValue(i));
                sb.append("\n");
            }
        }

        HttpLog.debug(request, String.format("发送请求 %s%nwith bodys: %n%s%nand headers: %n%s",
                request.url(), sb.toString(), request.headers()));

        Response response = chain.proceed(request);

        long t2 = System.nanoTime();//收到响应的时间

        //这里不能直接使用response.body().string()的方式输出日志
        //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
        //个新的response给应用层处理
        ResponseBody responseBody = response.peekBody(1024 * 1024);

        String body = responseBody.string();

        HttpLog.debug(request, String.format("接收响应: [%s] %n返回json:【%s】%nin %.1fms %nwith headers:%n%s",
                response.request().url(),
                body == null ? null : body.trim(),
                (t2 - t1) / 1e6d,
                response.headers()));

        return response;
    }
}